package com.easy.controller;

import com.easy.bean.Itinerary;
import com.easy.bean.ItineraryRequest;
import com.easy.bean.Itinerary_detail;
import com.easy.service.ItineraryService;
import com.easy.util.Page;
import com.easy.util.Result;
import com.easy.util.SYS;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin // 允许跨域访问
@RequestMapping("/itinerary")
public class ItineraryController {
    @Autowired
    ItineraryService itineraryService;

    @PostMapping
    public Result add(HttpServletRequest request, @RequestBody Itinerary itinerary){
      String token=request.getHeader(SYS.TOKEN_AUTHORIZATION);
      Object roleObj=com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
      Object idObj=com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
      if(idObj!=null){
          itinerary.setUser_id(Integer.valueOf(idObj.toString()));
      }
        Object obj = itineraryService.add(itinerary);
        return Result.success(obj);
    }

    @PutMapping
    public Result edit( HttpServletRequest request,@RequestBody Itinerary itinerary){
        // 获取当前用户信息
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 管理员可以编辑所有行程，普通用户只能编辑自己的行程
        if (roleObj != null && !"admin".equals(roleObj.toString())) {
            if (idObj != null) {
                Integer userId = Integer.valueOf(idObj.toString());
                // 检查行程是否属于当前用户
                Itinerary existingItinerary = itineraryService.one(itinerary.getId());
                if (existingItinerary != null && !existingItinerary.getUser_id().equals(userId)) {
                    return Result.fail(403, "只能编辑自己的行程");
                }
            }
        }

        Object obj = itineraryService.edit(itinerary);
        return Result.success(obj);
    }

    @DeleteMapping("/{id}")
    public Result del( HttpServletRequest request,@PathVariable("id") Integer id){
        // 获取当前用户信息
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 管理员可以删除所有行程，普通用户只能删除自己的行程
        if (roleObj != null && !"admin".equals(roleObj.toString())) {
            if (idObj != null) {
                Integer userId = Integer.valueOf(idObj.toString());
                // 检查行程是否属于当前用户
                Itinerary existingItinerary = itineraryService.one(id);
                if (existingItinerary != null && !existingItinerary.getUser_id().equals(userId)) {
                    return Result.fail(403, "只能删除自己的行程");
                }
            }
        }
        Object obj = itineraryService.del(id);
        return Result.success(obj);
    }

    @GetMapping("/{id}")
    public Result one( HttpServletRequest request,@PathVariable("id") Integer id){
        // 获取当前用户信息
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 管理员可以查看所有行程，普通用户只能查看自己的行程
        if (roleObj != null && !"admin".equals(roleObj.toString())) {
            if (idObj != null) {
                Integer userId = Integer.valueOf(idObj.toString());
                // 检查行程是否属于当前用户
                Itinerary existingItinerary = itineraryService.one(id);
                if (existingItinerary != null && !existingItinerary.getUser_id().equals(userId)) {
                    return Result.fail(403, "只能查看自己的行程");
                }
            }
        }
        Object obj = itineraryService.one(id);
        return Result.success(obj);
    }

    @GetMapping("all")
    public Result all( HttpServletRequest request,Itinerary itinerary){
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 普通用户只能查看自己的行程
        if (roleObj != null && !"admin".equals(roleObj.toString())) {
            if (idObj != null) {
                itinerary.setUser_id(Integer.valueOf(idObj.toString()));
            }
        }
        Object obj = itineraryService.all(itinerary);
        return Result.success(obj);
    }

    @GetMapping("page")
    public Result page( HttpServletRequest request,Page page, Itinerary itinerary){
        // 查询一共有多少条数据
        // 查询当前页要显示的数据
        // 将以上数据封装到page对象中
        // 返回page对象
        // 获取当前用户信息
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 普通用户只能查看自己的行程
        if (roleObj != null && !"admin".equals(roleObj.toString())) {
            if (idObj != null) {
                itinerary.setUser_id(Integer.valueOf(idObj.toString()));
            }
        }
        itineraryService.page(page, itinerary);
        return Result.success(page);
    }
    @GetMapping("pageWithDetails")
    public Result pageWithDetails( HttpServletRequest request,Page page, Itinerary itinerary){
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 普通用户只能查看自己的行程
        if (roleObj != null && !"admin".equals(roleObj.toString())) {
            if (idObj != null) {
                itinerary.setUser_id(Integer.valueOf(idObj.toString()));
            }
        }
        itineraryService.pageWithDetails(page, itinerary);
        return Result.success(page);
    }
    @GetMapping("getDetails/{id}")
    public Result getDetails(  HttpServletRequest request,@PathVariable("id") Integer id){
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 管理员可以查看所有行程详情，普通用户只能查看自己的行程详情
        if (roleObj != null && !"admin".equals(roleObj.toString())) {
            if (idObj != null) {
                Integer userId = Integer.valueOf(idObj.toString());
                // 检查行程是否属于当前用户
                Itinerary existingItinerary = itineraryService.one(id);
                if (existingItinerary != null && !existingItinerary.getUser_id().equals(userId)) {
                    return Result.fail(403, "只能查看自己的行程详情");
                }
            }
        }

        List<Itinerary_detail> details=itineraryService.getDetails(id);
        return Result.success(details);
    }
    @PostMapping("/generate")
    public Result generateItinerary(@RequestBody ItineraryRequest request, HttpServletRequest httpRequest) {
        try {
            // 从token中获取用户ID
            String token = httpRequest.getHeader(SYS.TOKEN_AUTHORIZATION);
            Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

            if (idObj == null) {
                return Result.fail(401,"用户未登录");
            }

            Integer userId = Integer.valueOf(idObj.toString());

            // 生成行程
            Itinerary itinerary = itineraryService.generateItinerary(
                    userId,
                    request.getCity(),
                    request.getDays(),
                    request.getPreferences()
            );

            return Result.success(itinerary);
        } catch (Exception e) {
            return Result.fail( 500, "生成行程失败: " + e.getMessage());
        }
    }

}
